/*
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-11-23 10:34:55
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-28 19:48:53
 */
import { TokenService } from '@package/service'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import router from './common/router/index.js'
import 'nprogress/nprogress.css'
import { pinias } from './common/pinia/index'

const { login, cachedView } = pinias
const userLogin = login?.()
const cachedStore = cachedView?.()
const whiteList = [
  '/login',
  '/noredirect',
  '/forgetPwd',
  '/registerSuccess',
  '/resePasswordSuccess',
  '/register',
  '/notice'
]
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (TokenService.getToken('Token')) {
    await hasToken(to, from, next)
  } else {
    await withoutToken(to, from, next)
  }
  NProgress.done()
})

async function hasToken(to, from, next) {
  if (to.path === '/login' || to.path === '/noredirect') {
    next({ path: '/home' })
    return
  }
  if (userLogin.menus.length || userLogin.user.id) {
    const { menus, auditInfo } = userLogin
    console.log('auditInfo: ', auditInfo)
    if ((menus.length && JSON.stringify(menus).indexOf(to.path) !== -1) || !!to.meta.noAuth) {
      if (auditInfo?.auditState === 4 || auditInfo?.supplierState === 3 || to.path === '/certification') {
        return next()
      }
      return next({ path: '/certification' })
    }
    next({ path: '/404' })
    return
  }
  try {
    await userLogin.getInfo()
    await userLogin.getUserMenus()
    await userLogin.getUserUnreadCount()
    await userLogin.getAuditDetail()
    next({ ...to, replace: true })
  } catch (err) {
    await userLogin.LogOut()
    await userLogin.clearUserInfo()
    Message.error(err)
    next({ path: '/' })
  }
}

async function withoutToken(to, from, next) {
  cachedStore.clearViews()
  if (whiteList.includes(to.path)) return next()
  next(`/login?redirect=${to.fullPath}`)
}
